import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/page/home/home_page_controller.dart';
import 'package:kkhousekeep/page/login/login_controller.dart';
import 'package:kkhousekeep/tools/string_ext.dart';
import 'package:kkhousekeep/widget/kk_sliver_persistent_header.dart';
import 'package:kkhousekeep/widget/scroll_page_view.dart';

import '../../models/home_community_entity.dart';
import '../../models/home_exist_new_mag_entity.dart';
import '../../models/home_notice_entity.dart';
import '../../widget/kk_default_tab_controller.dart';

class HomePage extends StatelessWidget {
  final UserType userType;

  const HomePage({
    Key? key,
    this.userType = UserType.tenant,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: HomeController(userType: userType),
      builder: (homeController) => RefreshIndicator(
          onRefresh: () => Future.delayed(
                const Duration(seconds: 2),
                () => homeController.loadNetworkData(),
              ),
          notificationPredicate: (_) {
            return true;
          },
          child: Container(
            padding: EdgeInsets.only(left: 32.w, right: 32.w),
            decoration: const BoxDecoration(
                image: DecorationImage(
              image: AssetImage("assets/images/home_bg.png"),
              fit: BoxFit.fill,
            )),
            child: KKDefaultTabController(
              onTabListener: (tabController) => homeController
                  .performClickTab(TabType.values[tabController.index]),
              length: homeController.tabsModels.length,
              builder: (tabController) => Column(
                children: [
                  Container(
                    color: Colors.transparent,
                    height: MediaQuery.of(context).padding.top,
                  ),
                  _builderTitleBarWidget(homeController),
                  Expanded(
                    child: NestedScrollView(
                      headerSliverBuilder: (context, innerBoxIsScrolled) =>
                          _buildHeader(context, homeController, tabController),
                      body: _builderBodyWidget(homeController, tabController),
                    ),
                  ),
                ],
              ),
            ),
          )),
    );
  }

  Widget _builderBodyWidget(
      HomeController homeController, TabController tabController) {
    if (homeController.userType == UserType.property) {
      return Container();
    }

    return Builder(builder: (context) {
      var handleFor = NestedScrollView.sliverOverlapAbsorberHandleFor(context);
      double marginHeight = handleFor.layoutExtent ?? 72.h;
      return Container(
        margin: EdgeInsets.only(top: marginHeight),
        height: double.infinity,
        child: TabBarView(
          controller: tabController,
          children: homeController.tabsModels.map((model) {
            return Obx(() => _builderTabBarViewItem(homeController, model));
          }).toList(),
        ),
      );
    });
  }

  Widget _builderTabBarViewItem(
      HomeController homeController, TabType tabType) {
    List<HomeCommunityObjList> dataList =
        homeController.communityMap[tabType] ?? [];

    if (tabType.id == 2) {
      return ListView.builder(
        padding: EdgeInsets.zero,
        itemExtent: 534.h,
        itemCount: dataList.length,
        itemBuilder: (context, index) {
          var entity = dataList[index];
          return InkWell(
            onTap: () => homeController.performClickCommunityItem(entity),
            child: Padding(
              padding: EdgeInsets.only(bottom: 34.h),
              child: Container(
                height: 502.h,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.h),
                    color: Colors.white),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      height: 400.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: NetworkImage(entity.showImages.isNotEmpty
                                ? entity.showImages[0]
                                : ''),
                            fit: BoxFit.fill,
                          ),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(8.h),
                            topRight: Radius.circular(8.h),
                          )),
                      width: double.maxFinite,
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 24.w, top: 12.h),
                      child: Text(
                        entity.title,
                        style: TextStyle(
                          color: const Color(0xFF6D6D6D),
                          fontSize: 28.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 24.w),
                      child: Text(
                        "发布时间：${entity.publishTime}",
                        style: TextStyle(
                            color: const Color(0xFF999999), fontSize: 24.sp),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      );
    }

    return GridView.builder(
      padding: EdgeInsets.zero,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 34.h,
        crossAxisSpacing: 30.w,
        childAspectRatio: 328.w / 269.h,
      ),
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        var entity = dataList[index];
        return InkWell(
          onTap: () => homeController.performClickCommunityItem(entity),
          child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.h), color: Colors.white),
            height: 268.h,
            child: Column(
              children: [
                Container(
                  height: 200.h,
                  margin: EdgeInsets.only(bottom: 12.h),
                  decoration: BoxDecoration(
                      image: DecorationImage(
                        image: NetworkImage(entity.showImages.isNotEmpty
                            ? entity.showImages[0]
                            : ''),
                        fit: BoxFit.fill,
                      ),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8.h),
                        topRight: Radius.circular(8.h),
                      )),
                  width: double.maxFinite,
                ),
                Text(
                  entity.title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: const Color(0xFF6D6D6D),
                    fontSize: 28.sp,
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _builderTitleBarWidget(HomeController homeController) {
    return InkWell(
      onTap: () => homeController.performClickAddress(),
      child: SizedBox(
        height: 124.h,
        child: Row(
          children: [
            Image(
              width: 60.w,
              height: 60.w,
              image: const AssetImage("assets/images/home_position.png"),
            ),
            Container(
              width: 532.w,
              padding: EdgeInsets.only(left: 8.w),
              child: Obx(() {
                var text = homeController.address.isEmpty
                    ? '请选择房屋'
                    : homeController.address.value;
                return Text(
                  text,
                  style: const TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                  ),
                  softWrap: false,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                );
              }),
            ),
            Obx(
              () => homeController.address.isNotEmpty
                  ? Icon(
                      Icons.keyboard_arrow_right,
                      size: 60.w,
                    )
                  : Container(),
            )
          ],
        ),
      ),
    );
  }

  Widget _builderBannerWidget(HomeController homeController) {
    return Obx(() => homeController.banners.isEmpty
        ? Container()
        : SizedBox(
            height: 380.h,
            child: ScrollPageView(
              onPageChanged: (index) =>
                  homeController.bannerIndex.value = index,
              indicatorColor: const Color(0xFFFFFFFF).withOpacity(0.6),
              checkedIndicatorColor: const Color(0xFF6D6D6D).withOpacity(0.6),
              indicatorRadius: 12.h,
              indicatorPadding: EdgeInsets.all(8.w),
              children: _builderBannerItems(homeController),
            ),
          ));
  }

  List<Widget> _builderBannerItems(HomeController homeController) {
    return homeController.banners
        .map(
          (banner) => GestureDetector(
            child: Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                    image: banner.imageUrl.isNetworkImage()
                        ? NetworkImage(banner.imageUrl) as ImageProvider
                        : AssetImage(banner.imageUrl),
                    fit: BoxFit.fill,
                  ),
                  borderRadius: BorderRadius.circular(32.w)),
              width: double.maxFinite,
            ),
          ),
        )
        .toList();
  }

  Widget _builderConvenientServiceWidget(
    HomeController homeController,
  ) {
    return _builderCommonTitleWidget(
      title: "便捷服务",
      controller: homeController,
      padding: homeController.banners.isEmpty
          ? EdgeInsets.only(top: 0, bottom: 28.h)
          : null,
      child: SizedBox(
        height: 136.w,
        child: GridView.count(
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          crossAxisCount: 4,
          children: homeController.serviceList
              .map((model) => InkWell(
                    onTap: () =>
                        homeController.performClickConvenientServiceItem(model),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset('assets/images/${model.iconName}',
                            width: 96.w, height: 96.w),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              model.name,
                              style: TextStyle(
                                fontSize: 28.sp,
                                color: const Color(0xFF6D6D6D),
                              ),
                            ),
                            Obx(
                              () => Visibility(
                                visible: _isShowNewMsg(
                                    homeController.existNewMsg.value, model),
                                child: Container(
                                  margin: EdgeInsets.only(top: 8.h),
                                  width: 10.w,
                                  height: 10.w,
                                  decoration: BoxDecoration(
                                    color: Colors.red,
                                    borderRadius: BorderRadius.circular(5.w),
                                  ),
                                ),
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                  ))
              .toList(),
        ),
      ),
    );
  }

  bool _isShowNewMsg(HomeExistNewMagObj obj, ServiceType type) {
    if (type == ServiceType.bill) {
      return obj.billExist;
    }

    if (type == ServiceType.notice) {
      return obj.noticeExist;
    }

    if (type == ServiceType.order) {
      return obj.workOrderExist;
    }
    return false;
  }

  Widget _builderNoticeWidget(HomeController controller) {
    return _builderCommonTitleWidget(
      title: "最新通知",
      controller: controller,
      padding: EdgeInsets.only(top: 64.h, bottom: 24.h),
      child: Obx(() {
        var height = controller.homeNoticeModels.length == 1
            ? (40 + 48 * controller.homeNoticeModels[0].length).h
            : (40 + 48 * 3).h;
        return Container(
          height: height,
          padding:
              EdgeInsets.only(left: 32.w, top: 16.h, right: 32.w, bottom: 24.h),
          decoration: BoxDecoration(
            color: const Color(0xB3FFFFFF),
            borderRadius: BorderRadius.circular(32.w),
          ),
          child: Swiper(
            duration: 800,
            autoplayDelay: 7000,
            key: GlobalKey(),
            loop: controller.homeNoticeModels.length < 2 ? false : true,
            itemBuilder: (BuildContext context, int index) {
              var model = controller.homeNoticeModels[index];
              return Column(
                children: model
                    .map((e) => _buildHomeNoticeItem(controller, e))
                    .toList(),
              );
            },
            autoplay: true,
            itemCount: controller.homeNoticeModels.length,
            scrollDirection: Axis.vertical,
          ),
        );
      }),
    );
  }

  Widget _builderCommunityWidget(
    HomeController controller,
  ) {
    return _builderCommonTitleWidget(
      title: "社区周边",
      controller: controller,
      padding: EdgeInsets.only(top: 48.h, bottom: 24.h),
      child: Container(),
    );
  }

  Widget _builderCommonTitleWidget({
    required String title,
    required HomeController controller,
    required Widget child,
    EdgeInsetsGeometry? padding,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: padding ?? EdgeInsets.only(top: 48.h, bottom: 28.h),
          child: Text(
            title,
            style: TextStyle(
              fontSize: 36.sp,
              color: const Color(0xFF333333),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        child,
      ],
    );
  }

  List<Widget> _buildHeader(BuildContext context, HomeController homeController,
      TabController tabController) {
    return [
      SliverToBoxAdapter(
        child: _builderBannerWidget(homeController),
      ),
      SliverToBoxAdapter(
        child: _builderConvenientServiceWidget(homeController),
      ),
      SliverToBoxAdapter(
        child: _builderNoticeWidget(homeController),
      ),
      SliverToBoxAdapter(
        child: Visibility(
          visible: homeController.userType != UserType.property,
          child: _builderCommunityWidget(homeController),
        ),
      ),
      SliverVisibility(
        visible: homeController.userType != UserType.property,
        sliver: SliverOverlapAbsorber(
          handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
          sliver: KKSliverPersistentHeader.hover(
            minHeight: 72.h,
            child: _builderTabBar(tabController, homeController, true),
          ),
        ),
      )
    ];
  }

  Widget _builderTabBar(
    TabController tabController,
    HomeController homeController,
    bool isSliverHeader,
  ) {
    return Obx(() => TabBar(
          controller: tabController,
          indicator: const BoxDecoration(),
          labelPadding:
              EdgeInsets.only(left: 0, top: 0, right: 16.w, bottom: 20.h),
          isScrollable: true,
          tabs: homeController.tabsModels.map((model) {
            bool isEnable = homeController.enableTabType.value.id == model.id;
            return Tab(
              child: Container(
                alignment: Alignment.center,
                height: 52.h,
                padding: EdgeInsets.only(left: 24.w, right: 24.w),
                decoration: BoxDecoration(
                  color: isEnable ? null : Colors.white,
                  borderRadius: BorderRadius.circular(26.w),
                  gradient: isEnable
                      ? const LinearGradient(
                          colors: [
                            Color(0xFF0a4ef1),
                            Color(0xFF7ae0e7),
                          ],
                        )
                      : null,
                ),
                child: Text(
                  model.tabName,
                  style: TextStyle(
                    color: isEnable ? Colors.white : const Color(0xFF999999),
                    fontSize: 32.sp,
                  ),
                ),
              ),
            );
          }).toList(),
        ));
  }

  Widget _buildHomeNoticeItem(
      HomeController controller, HomeNoticeObjList model) {
    return ClipRect(
      child: SizedBox(
        height: 48.h,
        child: InkWell(
          onTap: () => controller.performClickNoticeItem(model),
          child: Padding(
            padding: EdgeInsets.only(top: 8.h),
            child: Row(
              children: [
                Image.asset(
                  "assets/images/home_notice_icon.png",
                  width: 12.w,
                  height: 12.w,
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    padding: EdgeInsets.only(left: 18.w, right: 56.w),
                    width: double.infinity,
                    child: Text(
                      model.title,
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: const Color(0xFF6D6D6D),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
                Text(
                  model.publishTime,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.end,
                  style: TextStyle(
                      fontSize: 24.sp, color: const Color(0xFFCECECE)),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
